ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

How to Create & Use Custom Directive In Angular

In this tutorial, we will show you how to create a Custom Directive in Angular. The Angular directives help us to extend or manipulate the DOM. We can change the appearance, behavior, or layout of a DOM element using the directives. We will build a four directive example s and show you how to

  1. Create a custom directive using the @Directive decorator.
  2. We will create both custom attribute directive & custom Structural directive.
  3. How to setup selectors
  4. Pass value to it using the @input.
  5. How to respond to user inputs,
  6. Manipulate the DOM element (Change the Appearance) etc.

Angular Directives

The Angular has three types of directives.

  1. Components
  2. Structural Directives
  3. Attribute Directives

Components are directives with Template (or view). We know how to build Angular Components. Structural & Attribute directives do not have an associated view.

Structural directives change the DOM layout by adding and removing DOM elements. All structural Directives are preceded by the Asterix (*) symbol.

The Attribute directives can change the appearance or behavior of an element.

Creating Custom Attribute Directive

The Angular has several built-in attribute directives. Let us create a ttClass directive, which allows us to add class to an element. Similar to the Angular ngClass directive.

Create a new file and name it as tt-class.directive.ts. import the necessary libraries that we need.

                              

import { Directive, ElementRef, Input, OnInit } from '@angular/core'
                            
                        

Decorate the class with @Directive. Here we need to choose a selector (ttClass) for our directive. We name our directive as ttClassDirective.

                              
 
@Directive({
  selector: '[ttClass]',
})
export class ttClassDirective implements OnInit {
                            
                        

Our directive needs to take the class name as the input. The Input decorator marks the property ttClass as the input property. It can receive the class name from the parent component.

We use the same name same as the select name ttClass. This will enable us to use the property binding syntax <button> [ttClass]="' <blue>'" in the component.

You can also create more than @Input properties.

                              

@Input() ttClass: string;
                            
                        

We attach the attribute directive to an element, which we call the parent element. To change the properties of the parent element, we need to get the reference. Angular injects the parent element when we ask for the instance of the ElementRef in its constructor.

                              

constructor(private el: ElementRef) {
}
                            
                        

ElementRef is a wrapper for the Parent DOM element. We can access the DOM element via the property nativeElement. The classList method allows us to add the class to the element.

                              

ngOnInit() {
  this.el.nativeElement.classList.add(this.ttClass);
}
 
                            
                        

The complete code is as shown below.

                              
 
import { Directive, ElementRef, Input, OnInit } from '@angular/core'
 
@Directive({
  selector: '[ttClass]',
})
export class ttClassDirective implements OnInit {
 
  @Input() ttClass: string;
 
  constructor(private el: ElementRef) {
  }
 
  ngOnInit() {
    this.el.nativeElement.classList.add(this.ttClass);
  }
 
}
 
                            
                        

In the app.component.css and the CSS class blue

                              

.blue {
  background-color: lightblue;
}
 
                            
                        

Finally in the component template attach our customer directive ttClass to the button element.

                              

<button [ttClass]="'blue'">Click Me</button>
                            
                        

You can see from the image below, that class='blue' is inserted by Our Custom Directive.

image

The above is a simple imitation of ngClass. Have a look at the source code of ngClass

Creating Custom Structural Directive

Now, let us build a Custom Structural directive. Let us mimic the ngIf and create a custom directive, which we name it as ttIf. There is hardly any difference in creating a Attribute or structural directive.

We start of with creating a tt-if.directive.ts file and import the relevant modules.

                              

import { Directive, ViewContainerRef, TemplateRef, Input } from '@angular/core';
                            
                        

Decorate the class with @Directive with the selector as (ttIf). We name our directive as ttIfDirective.

                              
 
@Directive({ 
  selector: '[ttIf]' 
})
export class ttIfDirective  {
                            
                        

A variable to hold our if condition.

                              

_ttif: boolean;
                            
                        

Since, we are manipulating the DOM, we need ViewContainerRef and TemplateRef instances.

                              
 
  constructor(private _viewContainer: ViewContainerRef,
            private templateRef: TemplateRef<any>) {
  }
 
                            
                        

Our directive needs to take the if condition as the input. TheInput decorator marks the property ttIf as the input property. Note that we are using setter function,because we want the add or remove the content whenever the if condition changes.

We use the same name same as the select name ttIf. This will enable us to use theproperty binding syntax <div> <*ttIf="show"> in the template.

                              
 
  @Input()
  set ttIf(condition) {
    this._ttif = condition
    this._updateView();
  }
 
                            
                        

This is where all the magic happens. We use the createEmbeddedView method of the ViewContainerRef to insert the template if the condition is true. The clear removes the template from the DOM.

                              
 
  _updateView() {
    if (this._ttif) {
      this._viewContainer.createEmbeddedView(this.templateRef);
    }
    else {
      this._viewContainer.clear();
    }
 
                            
                        

That it. Remember to ttIfDirective in the declaration array of the app.module.ts. The complete code is as shown below.

                              
 
import { Directive, ViewContainerRef, TemplateRef, Input } from '@angular/core';
 
@Directive({ 
  selector: '[ttIf]' 
})
export class ttIfDirective  {
 
  _ttif: boolean;
 
  constructor(private _viewContainer: ViewContainerRef,
            private templateRef: TemplateRef<any>) {
  }
 
 
  @Input()
  set ttIf(condition) {
    this._ttif = condition
    this._updateView();
  }
 
  _updateView() {
    if (this._ttif) {
      this._viewContainer.createEmbeddedView(this.templateRef);
    }
    else {
      this._viewContainer.clear();
    }
  }
 
}
 
                            
                        
Component class
                              

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title: string = "Custom Directives in Angular";
  show=true;
}
                            
                        
Template
                              

<h1> {{title}} </h1>
 
Show Me
<input type="checkbox" [(ngModel)]="show">
 
<div *ttIf="show">
  Using the ttIf directive
</div>
 
<div *ngIf="show">
  Using the ngIf directive
</div>
 
 
                            
                        

Run the app and compare the ngIf & our custom directive ttIf side by side.

Why you need to specify *

Remove the * from our newly created ttIf directive. And you will get the error message

We use the *notation to tell Angular that we have a structural directive and we will be manipulating the DOM. It basically tells angular to inject the TemplateRef. To inject the templateRef, the Angular needs to locate the template. The * tells the Angular to locate the template and inject its reference as templateRef

Custom Directive Examples

The following two more Custom Directive Examples.Toggle & Tooltip directives

Toggle Directive

The following directive adds or removes the CSS class toggle from the Parent element. We do that by listening to the click event on the host element or parent element.

Angular makes this easy to listen to the events from the parent or host element using the @HostListener function decorator. We use it to decorate the function (onClick method in the example). It accepts the name of the event as the argument and invokes the decorated method whenever the user raises the event.

                              

 @HostListener('click')
 private onClick() {
                            
                        

The complete code of the ttToggleDirective is as follows.

                              
 
import { Directive, ElementRef, Renderer2, Input, HostListener, HostBinding } from '@angular/core'
 
@Directive({
  selector: '[ttToggle]',
})
export class ttToggleDirective {
 
  private elementSelected = false;
 
  constructor(private el: ElementRef) {
  }
 
  ngOnInit() {
  }
 
  @HostListener('click')
  private onClick() {
    this.elementSelected = !this.elementSelected;
    if (this.elementSelected) {
      this.el.nativeElement.classList.add('toggle')
    } else {
      this.el.nativeElement.classList.remove('toggle')
    }
  }
 
}
 
                            
                        

Add the following CSS Class

                              
 
.toggle {
  background-color: yellow
}
 
                            
                        

Use it as follows.

                              

<button ttToggle>Click To Toggle</button>
 
                            
                        

Tooltip Directive

The tooltip directive shows the tip whenever the user hovers over it. The directive uses the HostListener to listen to the mouseenter and mouseleave events.

The showHint method adds a span element into the DOM and sets its top & left position just below the host element. The removeHint removes it from the DOM.

                              

import { Directive, ElementRef, Renderer2, Input, HostListener } from '@angular/core'
 
@Directive({
  selector: '[ttToolTip]',
})
export class ttTooltipDirective {
 
  @Input() toolTip: string;
 
  elToolTip: any;
 
  constructor(private elementRef: ElementRef,
            private renderer: Renderer2) {
  }
 
  @HostListener('mouseenter') 
  onMouseEnter() {
    if (!this.elToolTip) { this.showHint(); }
  }
 
  @HostListener('mouseleave') 
  onMouseLeave() {
    if (this.elToolTip) { this.removeHint(); }
  }
 
  ngOnInit() {
  }
 
  removeHint() {
    this.renderer.removeClass(this.elToolTip, 'tooltip');
    this.renderer.removeChild(document.body, this.elToolTip);
    this.elToolTip = null;
  }
 
  showHint() {
 
    this.elToolTip = this.renderer.createElement('span');
    const text = this.renderer.createText(this.toolTip);
    this.renderer.appendChild(this.elToolTip, text);
 
    this.renderer.appendChild(document.body, this.elToolTip);
    this.renderer.addClass(this.elToolTip, 'tooltip');
    
    let hostPos = this.elementRef.nativeElement.getBoundingClientRect();
    let tooltipPos= this.elToolTip.getBoundingClientRect();
 
    let top = hostPos.bottom+10 ; 
    let left = hostPos.left;
 
    this.renderer.setStyle(this.elToolTip, 'top', `${top}px`);
    this.renderer.setStyle(this.elToolTip, 'left', `${left}px`);
  }
}
 
                            
                        

Add the following CSS Class

                              
 
.tooltip {
  display: inline-block;
  border-bottom: 1px dotted black; 
  position: absolute;
}
 
                            
                        

Use it as follows.

                              
 
<button ttToolTip toolTip="Tip of the day">Show Tip</button>